package org.gpf.game.tank.online;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/**
 * 坦克诞生的消息类
 * @author gaopengfei
 * @date 2015-4-22 下午12:29:21
 */
public class TankNewMsg implements Msg{

	int messageType = Msg.TANK_NEW_MSG;
	
	Tank tank;
	TankClient tc;

	/**
	 * 根据坦克的信息构造消息
	 * @param tank 坦克
	 */
	public TankNewMsg(Tank tank) {
		this.tank = tank;
	}

	/**
	 * 根据消息产生的场所构建新的消息
	 * @param tc 消息产生的场所 
	 */
	public TankNewMsg(TankClient tc) {
		this.tc = tc;
	}

	/**
	 * 向服务器的发送数据报
	 * @param ds 待发送数据报
	 * @param IP 服务器IP
	 * @param udpPort 服务器监听UDP端口
	 */
	@Override
	public void send(DatagramSocket ds,String IP,int udpPort) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos); // 将信息写入到字节数组，这里通过了流的包装
		try {
			dos.writeInt(messageType);
			dos.writeInt(tank.id);
			dos.writeInt(tank.x);
			dos.writeInt(tank.y);
			dos.writeInt(tank.dir.ordinal()); // 写入枚举类型数组的下标值
			dos.writeBoolean(tank.good);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		// 将字节数组封装成数据报
		byte[] buf = baos.toByteArray();
		try {
			DatagramPacket dp = new DatagramPacket(buf,buf.length,new InetSocketAddress(IP, udpPort) );
			ds.send(dp);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	/**
	 * 解析接收到的数据
	 * @param 接收到的数据的输入流
	 */
	public void parse(DataInputStream dis) {
		
		try {
			int id = dis.readInt();
			if (tc.myTank.id == id) { // 该消息是自己发送给自己的，不做任何响应
				return;
			}
			
			int x = dis.readInt();
			int y = dis.readInt();
			Dir dir = Dir.values()[dis.readInt()]; // 将下标值读取构造枚举
			boolean good = dis.readBoolean();
			boolean exist = false;
			for (int i = 0; i < tc.tanks.size(); i++) {
				Tank t = tc.tanks.get(i);
				if (t.id==id) {
					exist = true;
					break;
				}
			}
			if (!exist) {
				TankNewMsg tnMsg = new TankNewMsg(tc.myTank);
				tc.nc.send(tnMsg);
				
				Tank t = new Tank(x, y, good, dir, tc);
				t.id = id;
				tc.tanks.add(t);
			}
			System.out.println("id :" + id + ",x:" +x + ",y" + y +",dir:" +dir + ",good:" +good);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	
}
